package com.lvsc.sdaplacefinder.util;

import java.util.ArrayList;
import java.util.List;

import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.maps.GeoPoint;
import com.lvsc.sdaplacefinder.models.DirectionApi.Leg;
import com.lvsc.sdaplacefinder.models.DirectionApi.Route;
import com.lvsc.sdaplacefinder.models.DirectionApi.Step;

public class GoogleDirectionApi {
	public static PolylineOptions drawRoute(List<Route> routes) {
		PolylineOptions polylineOptions = new PolylineOptions();
		for (Route route : routes) {
			for (Leg leg : route.getLegs()) {
				polylineOptions.add(leg.getStartLatLng());
				for (Step step : leg.getSteps()) {

					polylineOptions.add(step.getEndLatLng());

				}
			}
		}
		return polylineOptions;
	}

	public static PolylineOptions drawRouteBis(Route route) {
		PolylineOptions polylineOptions = new PolylineOptions();
		List<GeoPoint> geoPoints = new ArrayList<GeoPoint>();
		geoPoints.addAll(decodePoly(route.getOverview_polyline().getPoints()));

		for (GeoPoint geoPoint : geoPoints) {
			polylineOptions.add(new LatLng(geoPoint.getLatitudeE6() / 1E6,
					geoPoint.getLongitudeE6() / 1E6));
		}
		return polylineOptions;
	}

	private static List<GeoPoint> decodePoly(String encoded) {

		List<GeoPoint> poly = new ArrayList<GeoPoint>();
		int index = 0, len = encoded.length();
		int lat = 0, lng = 0;

		while (index < len) {
			int b, shift = 0, result = 0;
			do {
				b = encoded.charAt(index++) - 63;
				result |= (b & 0x1f) << shift;
				shift += 5;
			} while (b >= 0x20);
			int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
			lat += dlat;

			shift = 0;
			result = 0;
			do {
				b = encoded.charAt(index++) - 63;
				result |= (b & 0x1f) << shift;
				shift += 5;
			} while (b >= 0x20);
			int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
			lng += dlng;

			GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6),
					(int) (((double) lng / 1E5) * 1E6));
			poly.add(p);
		}

		return poly;
	}
}
